using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.Services;
using Microsoft.Practices.CompositeUI.WinForms;
using Reflector.CodeModel;
using Reflector;

namespace DeblectorAddIn
{
    [Service(AddOnDemand=true)]
    public class FindFrameInAssemblyBrowser
    {
        [ServiceDependency]
        public IServiceProvider ReflectorApp
        {
            set { _reflector = value; }
        }
        Dictionary<string, IMethodDeclaration> _cache = new Dictionary<string, IMethodDeclaration>();
        IServiceProvider _reflector;
        public IMethodDeclaration Find(string assembly, string function)
        {
            if (_cache.ContainsKey(assembly + function))
                return _cache[assembly + function];
            IAssemblyManager mngr = (IAssemblyManager)_reflector.GetService(typeof(IAssemblyManager));
            foreach( IAssembly a in mngr.Assemblies )
            {
                if (a.Name == assembly)
                {
                    foreach( Reflector.CodeModel.IModule m in a.Modules )
                    {
                        foreach (IType t in m.Types)
                        {
                            if (t is ITypeDeclaration)
                            {
                                string nsp = ((ITypeDeclaration)t).Namespace;
                                if (string.IsNullOrEmpty(nsp))
                                    nsp = "";
                                else
                                    nsp += ".";
                                nsp += ((ITypeDeclaration)t).Name+".";
                                foreach (IMethodDeclaration met in ((ITypeDeclaration)t).Methods)
                                {
                                    string sComp = nsp+met.Name;
                                    if (sComp == function)
                                    {
                                        _cache[assembly + function] = met;
                                        return met;
                                    }

                                }
                            }
                        }
                    }
                }
            }
            return null;
        }
    }
}
